package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.FreemarkerServeice;
import com.dongdongshop.service.GoodService;
import com.dongdongshop.service.GoodsEditService;
import com.dongdongshop.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FreemarkerServiceImpl implements FreemarkerServeice {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Reference
    private GoodService goodService;

    @Reference
    private GoodsEditService goodsEditService;

    @Reference
    private ItemService itemService;

    @Override
    public void createPage(Long goodsId) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fw = null;
        try{
            Template template = configuration.getTemplate("item.ftl");
            //创建一个模板使用的数据集一般是map
            Map map = new HashMap();
            //根据goodsId查询goods对象
           TbGoods tbGoods = goodService.selectGoodsById(goodsId);
           // 根据goodsId查询详情表
           TbGoodsDesc tbGoodsDesc = goodsEditService.selectGoodsDescById(goodsId);
           //根据goodsId查询item的数据,spuid查询sku返回的一定是列表
            List<TbItem> itemList = itemService.selectItemListByGoodsId(goodsId);

            System.out.println(itemList);
            map.put("goods",tbGoods);
            map.put("goodsDesc",tbGoodsDesc);
            map.put("itemList",itemList);


            //创建一个writer对象一般创建一个FileWriter对象,指定生成的文件名
            fw = new FileWriter("D:\\goods\\"+goodsId+".html");
            // 调用模板对象的process方法输出文件
            template.process(map,fw);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
